import storage from "./storage";
import { getQueryString } from "./index";

export function setToken(token) {
  storage.setItem("token", token);
}

export function getToken() {
  return storage.getItem("token") || "";
}

export function isLogin() {
  return Boolean(getToken());
}

export function clearToken() {
  localStorage.clear();
  storage.removeItem("token");
  return true;
}

export function getAuthorizeUrl() {
  let url = `${
    process.env.apiUrl
  }/v1/account/oauth?callback=${encodeURIComponent(location.href)}`;
  // console.log(
  //   `${process.env.authorizeUrl}&redirect_uri=${encodeURIComponent(url)}`
  // );

  return `${process.env.authorizeUrl}&redirect_uri=${encodeURIComponent(url)}`;
}

getAuthorizeUrl();

const currentAuth = ["admin"];

export function getCurrentAuthority() {
  return currentAuth;
}

export function check(authority) {
  const current = getCurrentAuthority();
  return current.some(item => authority.includes(item));
}

function setTokenByOauth() {
  const token = getQueryString("token");

  if (token) {
    setToken(token);

    // 这个是为了清掉 token 和 tel
    let url = location.href.split("/#")[0];

    if (location.href.indexOf("?") > -1) {
      url = location.href.split("?")[0];
    }

    history.replaceState(null, null, url);
  }
}
setTokenByOauth();
